package com.xiaosu.red_travel.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

public class FileToUtil {
    /**
     * 把图片放到图片服务器上面并且返回响应的访问路径
     * @param fileName
     * @param file
     * @return
     */
    public static String updateImg(String fileName,File file){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-chengdu.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAI4G9Wu3Xyrvk5vhpoaaeY";
        String accessKeySecret = "KgCMrWo7GFj6ATyMkUr7rAQO3eUsCO";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest("niuzi12138", fileName+".jpg",file);
        // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传文件。
        ossClient.putObject(putObjectRequest);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        //获取文件访问路径
        String interviewUrl = ossClient.generatePresignedUrl("niuzi12138", fileName+".jpg", expiration).toString();
        // 关闭OSSClient。
        ossClient.shutdown();
        return interviewUrl;
    }
    public static String updateImg(String fileName,InputStream file){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-chengdu.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAI4G9Wu3Xyrvk5vhpoaaeY";
        String accessKeySecret = "KgCMrWo7GFj6ATyMkUr7rAQO3eUsCO";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest("niuzi12138", fileName+".jpg",file);
        // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传文件。
        ossClient.putObject(putObjectRequest);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        //获取文件访问路径
        String interviewUrl = ossClient.generatePresignedUrl("niuzi12138", fileName+".jpg", expiration).toString();
        // 关闭OSSClient。
        ossClient.shutdown();
        return interviewUrl;
    }

    /**
     * 输入流转换为byte数组
     * @param inputStream
     * @return
     */
    public static byte[]  inputStreamToByte(InputStream inputStream) {
        byte[] arr = new byte[0];
        try {
            arr = new byte[inputStream.available()];
            inputStream.read(arr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return arr;
    }

    /**
     * byte数组转换为输入流
     * @param bytes
     * @return
     */
    public static InputStream byteToInputStream(byte[] bytes){
        InputStream sbs = new ByteArrayInputStream(bytes);
        return sbs;
    }
    public static String getCheckCode() {
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=4;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }
    public static InputStream downloadWxImage(String url) throws FileNotFoundException {
        File file = null;

        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream= null;
        try {
            file = File.createTempFile("wx_image", ".png");
            //下载
            urlfile = new URL(url);
            inputStream = urlfile.openStream();
            outputStream= new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new FileInputStream(file);
    }
}
